/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.dict.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.dict.entity.HbAlg;
import vip.xiaonuo.biz.modular.dict.service.HbAlgService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.dict.entity.HbAlgteam;
import vip.xiaonuo.biz.modular.dict.mapper.HbAlgteamMapper;
import vip.xiaonuo.biz.modular.dict.param.HbAlgteamAddParam;
import vip.xiaonuo.biz.modular.dict.param.HbAlgteamEditParam;
import vip.xiaonuo.biz.modular.dict.param.HbAlgteamIdParam;
import vip.xiaonuo.biz.modular.dict.param.HbAlgteamPageParam;
import vip.xiaonuo.biz.modular.dict.service.HbAlgteamService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * hb_algteamService接口实现类
 *
 * @author gt
 * @date  2024/03/07 10:21
 **/
@Service
public class HbAlgteamServiceImpl extends ServiceImpl<HbAlgteamMapper, HbAlgteam> implements HbAlgteamService {

    @Resource
    private HbAlgService hbAlgService;
    @Override
    public JSONObject page(HbAlgteamPageParam hbAlgteamPageParam) {

        List<HbAlg> algList = hbAlgService.list();

        QueryWrapper<HbAlgteam> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HbAlgteam::getPId, 0);
        if(ObjectUtil.isNotEmpty(hbAlgteamPageParam.getAlgName())) {
            queryWrapper.lambda().like(HbAlgteam::getAlgName, hbAlgteamPageParam.getAlgName());
        }
        if(ObjectUtil.isNotEmpty(hbAlgteamPageParam.getAlgKeyId())) {
            queryWrapper.lambda().like(HbAlgteam::getAlgKeyId, hbAlgteamPageParam.getAlgKeyId());
        }
        if(ObjectUtil.isNotEmpty(hbAlgteamPageParam.getAlgEnName())) {
            queryWrapper.lambda().like(HbAlgteam::getAlgEnName, hbAlgteamPageParam.getAlgEnName());
        }
        if(ObjectUtil.isNotEmpty(hbAlgteamPageParam.getAlgVersion())) {
            queryWrapper.lambda().like(HbAlgteam::getAlgVersion, hbAlgteamPageParam.getAlgVersion());
        }
        if(ObjectUtil.isNotEmpty(hbAlgteamPageParam.getNickName())) {
            queryWrapper.lambda().like(HbAlgteam::getNickName, hbAlgteamPageParam.getNickName());
        }
        if(ObjectUtil.isNotEmpty(hbAlgteamPageParam.getAlgLevel())) {
            queryWrapper.lambda().like(HbAlgteam::getAlgLevel, hbAlgteamPageParam.getAlgLevel());
        }
        if(ObjectUtil.isAllNotEmpty(hbAlgteamPageParam.getSortField(), hbAlgteamPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(hbAlgteamPageParam.getSortOrder());
            queryWrapper.orderBy(true, hbAlgteamPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(hbAlgteamPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(HbAlgteam::getId);
        }


        Page<HbAlgteam> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);

        Map<String,HbAlg> keyToALg = new HashMap<>();
        for (HbAlg hbAlg : algList) {
            String key = String.valueOf(hbAlg.getId());
            keyToALg.put(key,hbAlg);
        }
        List<HbAlgteam> records = page.getRecords();


        JSONArray respArr = new JSONArray();


        List<HbAlgteam> allList = this.list();
        for (HbAlgteam record : records) {
            JSONObject teamjson = JSONUtil.parseObj(record);
            JSONArray algArr = new JSONArray();
            for (HbAlgteam hbAlgteam : allList) {
                if(record.getId().equals(hbAlgteam.getPId())){
                    if(ObjectUtil.isNotEmpty(hbAlgteam.getPId())){
                        HbAlg hbAlg = keyToALg.get(String.valueOf(hbAlgteam.getAlgKeyId()));
                        hbAlg.setId(hbAlgteam.getId());
                        algArr.add(hbAlg);
                    }
                }
            }
            if(ObjectUtil.isNotEmpty(algArr)){
                teamjson.putOnce("children",algArr);
            }
            respArr.add(teamjson);
        }

        JSONObject entries = JSONUtil.parseObj(page);
        entries.remove("records");
        entries.putOnce("records",respArr);
        return entries;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(HbAlgteamAddParam hbAlgteamAddParam) {
        /**
         * 新增 如果是算法组  只传递名称 team_Name=？  pid=0
         * 如果新增的是算法                         pid=算法组的id       algKeyId=算法的id   algENName=算法列表的algCode
         */
        HbAlgteam hbAlgteam = BeanUtil.toBean(hbAlgteamAddParam, HbAlgteam.class);
        this.save(hbAlgteam);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(HbAlgteamEditParam hbAlgteamEditParam) {
        HbAlgteam hbAlgteam = this.queryEntity(String.valueOf(hbAlgteamEditParam.getId()));
        BeanUtil.copyProperties(hbAlgteamEditParam, hbAlgteam);
        this.updateById(hbAlgteam);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer id) {
        // 执行删除
        HbAlgteam byId = this.getById(id);
        if(byId.getPId().equals("0")){
            this.baseMapper.deleteByPid(byId.getPId());
            this.delete(id);
        }
        this.baseMapper.deleteById(id);
    }

    @Override
    public HbAlgteam detail(HbAlgteamIdParam hbAlgteamIdParam) {
        return this.queryEntity(String.valueOf(hbAlgteamIdParam.getId()));
    }

    @Override
    public HbAlgteam queryEntity(String id) {
        HbAlgteam hbAlgteam = this.getById(id);
        if(ObjectUtil.isEmpty(hbAlgteam)) {
            throw new CommonException("hb_algteam不存在，id值为：{}", id);
        }
        return hbAlgteam;
    }
}
